package com.vpen.server.handler;

import com.vpen.server.codec.CommandDecoder;
import com.vpen.server.codec.FileDecoder;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2024/4/4 22:56
 */
@Slf4j
@Component
public class ServerChannelInitializerImpl  extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // outbound
        pipeline
                .addLast("byteEncoder", new ByteArrayEncoder())
        ;

        // inbound
        pipeline
                .addLast(new LoggingHandler(LogLevel.INFO))
                .addLast("idleStateHandler", new IdleStateHandler(60, 60, 0, TimeUnit.SECONDS))
                .addLast("fileDecoder", new FileDecoder())
                .addLast("delimiterDecoder", new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[]{0x7e})))
                .addLast("commandDecoder",new CommandDecoder())
                .addLast("commandHandler",new CommandHandler())
                .addLast("fileHandler",new FileHandler())

        ;
    }
}
